﻿using Newtonsoft.Json;
using RMS.Common;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;

namespace RMS.Common.Error
{
    public class MVCErrorAttribute : ActionFilterAttribute, IExceptionFilter
    {

        /// <summary>
        /// 异常
        /// </summary>
        /// <param name="filterContext">异常上下文</param>
        public void OnException(ExceptionContext filterContext)
        {
            var result = new CommonOutPutVm();
            NLogHelper nlog = new NLogHelper();
            Exception Error = filterContext.Exception;
            #region 获取异常信息，入库保存
            try
            {
                ErrorLog log = Error.ToHttpErrorLog();
                result.Message = Error.GetInnerMessage();
                log.Save();
            }
            catch (Exception e)
            {
                result.Message = "异常处理错误：" + Error.Message;
                nlog.Error(Error);
                e.SaveLogException();
            }
            #endregion
            #region 返回错误信息对象输出错误信息
            finally
            {
                var request = filterContext.HttpContext.Request;
                #region POST
                if (request.HttpMethod.Equals("POST", StringComparison.OrdinalIgnoreCase))
                {
                    JsonResult json = new JsonResult();
                    json.Data = result;
                    json.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
                    filterContext.Result = json;//返回错误信息
                }
                #endregion
                #region GET
                else if (request.HttpMethod.Equals("GET", StringComparison.OrdinalIgnoreCase))
                {
                    filterContext.Result = new RedirectResult("~/Error/Index?msg=" + result.Message.UrlEncode());
                }
                #endregion
                #region 其他
                else
                {
                    filterContext.Result = new HttpUnauthorizedResult();
                }
                #endregion
                filterContext.ExceptionHandled = true;
                filterContext.HttpContext.Response.StatusCode = 200;
            }
            #endregion
        }
    }
}
